import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
    // const count = ref(0)
    // const doubleCount = computed(() => count.value * 2)
    // function increment() {
    //   count.value++
    // }
  
    // return { count, doubleCount, increment }
  
    const cartList = ref([])

    //加入购物车
    const addItem = (payload) => {
        const index = cartList.value.findIndex(item => item.id==payload.id)
        if(index>-1){
            cartList.value[index].count++
        }else{
            cartList.value.push({
                ...payload,
                count:1,
                checked:false
            })
        }
    }
    //删除购物车
    const deleteCart = (id) => {
        cartList.value=cartList.value.filter(item => item.id!=id)
    }

    //购物车总数
    const zongList = computed(()=>{
        let res = 0
        cartList.value.forEach(item =>{
            res+=item.count
        })
        return res
    })

    //购物车总额
    const zongPrice = computed(()=>{
        let res = 0
        cartList.value.forEach(item =>{
            if(item.checked){
                res+=item.count * item.price
            }
        })
        return res.toFixed(2)
    })
    return{cartList,addItem,deleteCart,zongList,zongPrice}
},{
    persist: true,
  })